#!/usr/bin/env python2.5

# 
# Copyright (c) 2007 Mads D. Kristensen.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# ============================================================================
# Name        : main.py
# Author      : Mads Daroe Kristensen
# Version     : 0.1
# Description : AugIm image manipulation program.
# ============================================================================

import gtk, gtk.glade
import hildon, osso
from imagebrowser import ImageBrowser
from imageeditor import ImageEditor
from taskmonitor import TaskMonitor
from config_window import ConfigWindow
from defines import Defines
from os.path import exists
from os import mkdir
from ConfigParser import ConfigParser
from scavenger import Scavenger
import sys

class AugIm_UI(hildon.Program):
    """Maemo (GTK) frontend for the AugIM image handling program."""
    
    GLADEFILE = 'augim_main.glade'

    def __init__(self):
        hildon.Program.__init__(self)
        
        # Read in the .glade file.
        self.widgets = gtk.glade.XML(self.GLADEFILE)

        # Set local vars.
        self.config = ConfigParser()
        try:
            self.config.read(Defines.CONFIG_FILE)
        except:
            # If an error occurs reading the config file a fresh config 
            # parser is created - just in case.
            self.config = ConfigParser()
        self.fullscreen = False
        self.image_browser = ImageBrowser(self, self.widgets)
        self.image_editor = ImageEditor(self, self.widgets)
        self.task_monitor = TaskMonitor(self, self.widgets)
        self.config_window = ConfigWindow(self, self.widgets, self.config)
 #       self.about = About(self, self.widgets)
        self.mode = 'browse'

        # Register with DBus.
        self.osso_c = osso.Context('AugIM', '0.1.0', False)
        osso_rpc = osso.Rpc(self.osso_c)
        osso_rpc.set_rpc_callback('edu.daimi.augim',\
                                  'edu/daimi/augim',\
                                  'edu.daimi.augim',\
                                  self.cb_osso, self.osso_c)
        
        # Initialize the image browser. Load in any images in $HOME/MyImages.
        try:
            self.image_browser.load_images_from_path(Defines.IMAGE_PATH)
        except OSError:
            pass
    
    def __wrap(self, text, width):
        result = []
        while True:
            if width > len(text):
                # The last line has been reached.
                result.append(text)
                break
            x = width
            # Check for newlines within the next piece of text. 
            newline = text[:x].find('\n')
            if newline != -1:
                # There is a newline char in the text.
                result.append(text[:newline+1])
                text = text[newline+1:]
                continue
            while x > 0 and text[x] != ' ':
                x -= 1
            if x == 0:
                # The token is larger than the line.
                result.append(text[:width-2] + '-\n')
                text = text[width-2:]
            else:
                result.append(text[:x] + '\n')
                text = text[x+1:]
        return ''.join(result)

    def popup_message(self, message):
        note = osso.SystemNote(self.osso_c)
        note.system_note_infoprint(self.__wrap(message, 40))
    
    def __get_active_window(self):
        if self.mode == 'browse':
            return self.image_browser
        elif self.mode == 'edit':
            return self.image_editor
        elif self.mode == 'task':
            return self.task_monitor
        elif self.mode == 'config':
            return self.config_window
    
    def __set_active_window(self, mode):
        self.mode = mode
        if self.mode == 'browse':
            self.image_browser.show()
        elif self.mode == 'edit':
            self.image_editor.show(self.image_browser.original_image)
        elif self.mode == 'task':
            self.task_monitor.show()
        elif self.mode == 'config':
            self.config_window.show()
    
    def set_mode(self, mode):
        old_window = self.__get_active_window()
        self.fullscreen = old_window.fullscreen
        self.__set_active_window(mode)
        old_window.hide()

    def cb_osso (self, interface, method, arguments, user_data):
        print 'received an OSSO RPC.'

    def run (self):
        self.image_browser.show()
        gtk.main()

if __name__ == '__main__':
    # Check that the image path and the settings dirs exist.
    if not exists(Defines.IMAGE_PATH):
        mkdir(Defines.IMAGE_PATH)
    if not exists(Defines.CONFIG_DIR):
        mkdir(Defines.CONFIG_DIR)

    # Start the application.
    gtk.gdk.threads_init()
    app = AugIm_UI()
    app.run()
    
    Scavenger.shutdown()
    sys.exit(0)
